package com.wshl.aijiuunion.controller.activity;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.OkGo;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.DialogUtil;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.view.bean.JIamenSheiBeiBean;
import com.wshl.aijiuunion.view.widget.AreaDialog;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;
import com.wshl.aijiuunion.view.widget.RoundCornerImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/29 0029
 * 合作设备
 */
public class JIamengShebeiActivity extends TakePhotoActivity implements DialogUtil.OnBottomDilogClick, RequestModel.onSendcodeListener {


    private static final int STORE = 1;
    private static final int YINGYEZHIZHAO = 2;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_mobile)
    EditText tvMobile;
    @BindView(R.id.et_verifycode)
    EditText etVerifycode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.et_tuijianma)
    EditText etTuijianma;
    @BindView(R.id.et_company)
    EditText etCompany;
    @BindView(R.id.img_yingyezhizhao)
    RoundCornerImageView imgYingyezhizhao;
    @BindView(R.id.img_store)
    RoundCornerImageView imgStore;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_confirm)
    NofastClickTextview tvConfirm;
    private CompressConfig compressConfig;
    private TakePhoto takePhoto;
    private Uri imageUri;
    private CropOptions cropOptions;

    private RequestModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setContentView(R.layout.activity_jiamengshebei);
        ButterKnife.bind(this);
        BarUtils.setWhiteStatusBarForActivity(this);
        //图片选择器
        takePhoto = getTakePhoto();
        //压缩图片(压缩到200k以内)
        compressConfig = new CompressConfig.Builder().setMaxSize(200 * 1024).create();
        takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框
        //图片裁剪方式
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();

        DialogUtil.setOnBottomDilogClick(this);
        model = new RequestModel();
        model.setOnsendCodeListener(this);
        tvTopTitle.setText("合作设备");
        String mobile = SPUtils.getInstance().getString(GlobConstant.MOBILE);
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        if (!TextUtils.isEmpty(token)&&!TextUtils.isEmpty(mobile)) {
            tvMobile.setText(mobile);
        }

    }

    private String province_id, city_id, area_id;
    private String storeUrl, yingyizhizhaoUrl;

    private void showAreaDialog() {

        final AreaDialog dialog = new AreaDialog(this, R.style.recharge_pay_dialog);
        dialog.show();
        dialog.setNoOnclickListener(new AreaDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                dialog.dismiss();
            }
        });

        dialog.setYesOnclickListener(new AreaDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                dialog.dismiss();
            }

            @Override
            public void getItemContent(String province, String cityname, String countryname, String area) {

            }


            @Override
            public void getcontent(String address) {
                LogUtils.i("address:" + address);
                tvAddress.setText(address);

            }

            @Override
            public void setProvinceid(String selsectItem1id) {
                LogUtils.i("市:" + selsectItem1id);
                city_id = selsectItem1id;
            }

            @Override
            public void setCityid(String selsectItem2id) {
                LogUtils.i("县id:" + selsectItem2id);
                area_id = selsectItem2id;
            }

            @Override
            public void setCountryid(String selsectItem3id) {

            }

            @Override
            public void setAreaid(String selsectItem4id) {
                LogUtils.i("省id:" + selsectItem4id);
                province_id = selsectItem4id;

            }
        });
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = AbsListView.LayoutParams.MATCH_PARENT;
        lp.y = 0;
        //设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        String originalPath = result.getImage().getOriginalPath();
        String compressPath = result.getImage().getCompressPath();//压缩路径
        LogUtils.e("头像路径:" + originalPath);
        LogUtils.e("头像压缩路径:" + compressPath);

        uploadImg(compressPath);//上传图片


    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        LogUtils.i("取消");
    }


    private void uploadImg(final String imgpath) {

        model.uploadImg(this, imgpath, new RequestCallback() {
            @Override
            public void onSuccess(String response) {


                if (type == STORE) {
                    storeUrl = response;
                    GlideUtils.loadImage(JIamengShebeiActivity.this, imgpath, imgStore);

                } else if (type == YINGYEZHIZHAO) {
                    yingyizhizhaoUrl = response;
                    GlideUtils.loadImage(JIamengShebeiActivity.this, imgpath, imgYingyezhizhao);
                }


            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }


    private int type = YINGYEZHIZHAO;

    @OnClick({R.id.img_back, R.id.tv_send_code, R.id.img_yingyezhizhao, R.id.img_store, R.id.tv_address, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.tv_send_code:
                String mobile = tvMobile.getText().toString();
                model.sendCode(JIamengShebeiActivity.this, mobile);
                break;
            case R.id.img_yingyezhizhao:
                type = YINGYEZHIZHAO;
                DialogUtil.showBottomDialog(JIamengShebeiActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.img_store:
                type = STORE;
                DialogUtil.showBottomDialog(JIamengShebeiActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.tv_address:
                showAreaDialog();
                break;
            case R.id.tv_confirm:
                String truename = etName.getText().toString().trim();
                String moboile = tvMobile.getText().toString();
                String verifycode = etVerifycode.getText().toString().trim();
                String tuijianma = etTuijianma.getText().toString().trim();
                String company = etCompany.getText().toString().trim();

                JIamenSheiBeiBean bean = new JIamenSheiBeiBean();

                bean.setTrurname(truename);
                bean.setMobile(moboile);
                bean.setCode(verifycode);
                bean.setTuijianma(tuijianma);
                bean.setCompany(company);
                bean.setAreaid(area_id);
                bean.setProvinceid(province_id);
                bean.setCityid(city_id);
                bean.setStoreurl(storeUrl);
                bean.setYingyizhizhaourl(yingyizhizhaoUrl);


                model.jiaMengShebei(JIamengShebeiActivity.this, bean, new RequestCallback() {
                    @Override
                    public void onSuccess(String response) {

                        ToastUtils.showShort("提交成功");
                        JIamengShebeiActivity.this.finish();
                    }

                    @Override
                    public void onError(int code) {

                    }

                    @Override
                    public void onIntentError() {

                    }
                });
                break;
        }
    }


    //获取头像
    private void getImage(final String title) {
        XXPermissions.with(this)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                        File file = new File(GlobConstant.SDCARD_DIR, GlobConstant.IMAGE_CACHE_DIR + System.currentTimeMillis() + ".png");
                        if (!file.getParentFile().exists())
                            file.getParentFile().mkdirs();
                        imageUri = Uri.fromFile(file);

                        takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框
                        if (title.equals("拍照")) {
                            takePhoto.onPickFromCapture(imageUri);
                            // takePhoto.onPickMultiple(3);

                        } else if (title.equals("相册")) {
                            // takePhoto.onPickMultiple(3);
                            takePhoto.onPickFromGallery();

                        }


                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置
                        if (quick) {
                            DialogUtil.showNormaldialog(JIamengShebeiActivity.this, "请手动打开权限", false, true);
                            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                                @Override
                                public void setConfirm() {
                                    XXPermissions.gotoPermissionSettings(JIamengShebeiActivity.this);
                                }

                                @Override
                                public void setCancel() {
                                    JIamengShebeiActivity.this.finish();

                                }

                                @Override
                                public void getInput(String input) {

                                }
                            });

                        }

                    }
                });
    }

    @Override
    public void setTitle1(String title) {
        getImage(title);
    }

    @Override
    public void setTitle2(String title) {
        getImage(title);
    }

    @Override
    public void setTitle3(String title) {

    }

    @Override
    public void start(int s) {
        tvSendCode.setClickable(false);
        tvSendCode.setText(s + "s");

    }

    @Override
    public void end() {
        tvSendCode.setClickable(true);
        tvSendCode.setText("重新发送");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
